from action import *
from prompt import *
from tools import prase_json_from_response


def execute_plan(question):
    response = LLM(TABLE_PLAN_PROMPT_MY.format(question=question))
    plan = prase_json_from_response(response)

    for sub_plan in plan:
        print(sub_plan)

    # 执行plan
    plan_map = {"提取法院代字": extract_court_representative, "查询": retrieve, "统计": stat, "排序": order,
                "总结": summary, "多次查询": multi_retrieve,
                "条件筛选": filter_list, "总金额计算": calculate_cash}
    answer = []
    data = None
    sub_answer = ''
    index = 1
    for sub_plan in plan:
        try:
            if sub_plan["是否需要前序结果"] == 'False':
                question = sub_plan['问题']
            else:
                question = str(sub_answer) + '\n' + sub_plan['问题']
            sub_answer, data = plan_map[sub_plan['操作']](question, data)
            # 如果sub_answer为dict，则将dict转换为str
            if isinstance(sub_answer, dict):
                sub_answer = str(sub_answer)
            answer.append(sub_answer)
            index += 1
        except Exception as e:
            # 获取异常的堆栈跟踪信息
            traceback_info = traceback.format_exc()
            # 打印堆栈跟踪信息
            print(f"执行子流程发生异常：{traceback_info}")
            pass
    return answer
